package com.wlgc.service.impl;

import com.wlgc.entity.ChatList;
import com.wlgc.entity.ChatMessage;
import com.wlgc.entity.vo.ChatListVO;
import com.wlgc.mapper.ChatListMapper;
import com.wlgc.mapper.ChatMessageMapper;
import com.wlgc.service.ChatService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatListMapper chatListMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    public String selectAssociation(String fromUser, String toUser) {
        return null;
    }

    @Override
    public void isFirstChat(String fromUser, String toUser) {

    }

    @Override
    public void saveMessage(ChatMessage chatMessage) {

    }

    @Override
    //查询发送方端聊天列表
    public List<ChatListVO> getFromUserChatList(Long fromUid) {

        List<ChatListVO> chatListVOList = new ArrayList<>();;
        ChatListVO chatListVO = new ChatListVO();
        //1.查询当前用户作为发送方的聊天列表
        List<ChatList> chatListList = chatListMapper.getByfromUid(fromUid);
        //2.查询当前聊天列表的最后一条消息

        for (ChatList chatList:chatListList) {
            BeanUtils.copyProperties(chatList,chatListVO);
            //使用当前listId查询聊天消息详细表
            ChatMessage chatMessage1 =  new ChatMessage();
            chatMessage1.setId(chatList.getId());
            ChatMessage chatMessage = chatMessageMapper.getLastMessage(chatMessage1);
            //查询到最后一条消息直接打包返回
            if(chatMessage!=null){
                chatListVO.setContent(chatMessage.getContent());
                chatListVO.setSendTime(chatMessage.getSendTime());
                chatListVOList.add(chatListVO);
            }else {
                //未查询到则将发送方uid和接收方uid互换查询聊天消息详细表
                chatMessage1.setId(null);
                chatMessage1.setFromUid(chatList.getToUid());
                chatMessage1.setToUid(chatList.getFromUid());
                ChatMessage lastMessage = chatMessageMapper.getLastMessage(chatMessage1);
                //查询到就返回最后一条消息
                chatListVO.setContent(lastMessage.getContent());
                chatListVO.setSendTime(lastMessage.getSendTime());
                chatListVOList.add(chatListVO);
            }

        }

        return chatListVOList;
    }

    @Override
    public void updateWindows(String fromUser, String toUser) {

    }

    @Override
    public void resetWindows(String username) {

    }
}
